import { isEmpty } from "lodash";

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function buildTreeData(
  data?: any[],
  id?: string,
  name?: string,
  parentId?: string,
  parentName?: string,
  children?: string,
) {
  if (!data) {
    return [];
  }
  const config = {
    id: id || 'id',
    name: name || 'name',
    parentId: parentId || 'parentId',
    parentName: parentName || 'parentName',
    childrenList: children || 'children',
  };

  const childrenListMap = {};
  const nodeIds = {};
  const tree: any[] = [];
  data.forEach((item: { id: string; name: string; key: string; title: string; value: any }) => {
    const d = item;
    const pId = d[config.parentId];
    if (childrenListMap[pId] == null) {
      childrenListMap[pId] = [];
    }
    d.key = d[config.id];
    d.title = d[config.name];
    d.value = d[config.id];
    nodeIds[d[config.id]] = d;
    childrenListMap[pId].push(d);
  });

  data.forEach((item: any) => {
    const d = item;
    const pId = d[config.parentId];
    if (nodeIds[pId] == null) {
      d[config.parentName] = '';
      tree.push(d);
    }
  });

  tree.forEach((t: any) => {
    adaptToChildrenList(t);
  });

  function adaptToChildrenList(item: any) {
    const o = item;
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      o[config.childrenList].forEach((child: any) => {
        const c = child;
        c[config.parentName] = o[config.name];
        adaptToChildrenList(c);
      });
    }
  }
  return tree;
}


export enum SortType {
  ASC, DESC
}

/**
 * 
 * @param arr 需要排序的数组
 * @param sortName 排序字段名字
 * @param type 排序类型
 * @param childrenName 树形组件子字段排序
 * @returns 排序后的数组
 */
export function MySort(arr: any[], sortName?: string, type?: SortType, childrenName?: string): any[] {
  if (isEmpty(arr)) {
    return [];
  }
  if (isEmpty(sortName)) {
    return arr.sort((a, b) => {
      return type == SortType.ASC ? a - b : b - a;
    });
  }
  if (sortName) {
    arr.sort((a, b) => {
      return type == SortType.ASC ? a[sortName] - b[sortName] : b[sortName] - a[sortName];
    })
    if (childrenName) {
      arr.forEach(value => {
        MySort(value[childrenName], sortName, type, childrenName);
      })
    }
  }
  return arr;
}